package com.longrise.android.byjk.plugins.dealsituation.cachecourse;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.longrise.LEAP.Base.IO.JSONSerializer;
import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.common.base.RxManager;
import com.longrise.android.byjk.common.Control;
import com.longrise.android.byjk.common.DownloadConstants;
import com.longrise.android.byjk.common.FolderConstants;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.CourseTrainDirBean;
import com.longrise.android.byjk.model.CurrcluSubTitle;
import com.longrise.android.byjk.model.CurriclunTitle;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.datasource.local.sp.CacheUtils;
import com.longrise.common.utils.DZZWTools;
import com.longrise.android.byjk.utils.DialogUtil;
import com.longrise.android.byjk.utils.FileUtil;
import com.longrise.common.utils.NetUtil;
import com.longrise.common.utils.PrintLog;
import com.longrise.android.byjk.utils.Tracker_Google;
import com.longrise.android.upload_offline.DBHelper;
import com.longrise.filedownloader.DownloadManager;
import com.longrise.filedownloader.DownloadService;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by xkj on 2016/3/11.
 * 添加缓存的页面
 */
public class AddDownloadActivity extends BaseActivity implements ExpandableListView.OnChildClickListener,
        View.OnClickListener {

    private static final String TAG = "AddDownloadActivity";
    public static final String COURSE_ID = "COURSE_ID";
    public static final String COURSE_BEAN = "COURSE_BEAN";
    public static final int REQUEST_CODE = 232;

    private ExpandableListView mElv;
    private String mCourseid; // 课程id
    private List<List<CurrcluSubTitle>> mCurrcluSubTitlesList; //child
    private AddDownLoadAdapter mAdapter;
    private TextView mTvConfirm;
    private List<CurriclunTitle> mCurriclunTitles; //parent
    private List<CurrcluSubTitle> mCheckedChildlist; //被选择的需要下载的item;
    private TextView mTvCheckAll;
    private boolean mIsCheckAll = false;
    private String mCourseImageUrl; //课程图片地址
    private DBHelper mDBHelper;
    private SQLiteDatabase db;
    private String localCourseImagePath; //课程封面图片的本地缓存地址
    private String mTeachername;
    private String mCourseName;
    private String deifinition;
    private TextView mTvNum;
    private ImageView mIvright;
    private List<CurrcluSubTitle> mNeedToDownChildlist; //被选择的需要下载的item;

//    private PopupWindow mPWindow;

    private String mExpiretime;
    private LinearLayout mRlNum;

    private DownloadManager mDownloadManager;
    private EntityBean mBean;
    private Toolbar mToolbar;
    private RelativeLayout mRlright;
    private TextView mTvsd;
    private RxManager mRxManager;
    private Disposable mSdsubscribe;

    public void setData(String courseid, EntityBean bean) {
        this.mCourseid = courseid;
        this.mBean = bean;
    }

    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.lfview_adddownload;
    }

    @Override
    protected void onStart() {
        super.onStart();
        getSdRemain();
    }

    @Override
    public void initView() {
        mToolbar = (Toolbar) findViewById(R.id.byjk_toolbar);
        mToolbar.setTitle(AppUtil.getString(R.string.adddownload_title));
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_close_main);
        mRlright = (RelativeLayout) findViewById(R.id.bb_toolbar_right_rl);
        mRlright.setVisibility(View.VISIBLE);
        mIvright = (ImageView) findViewById(R.id.iv_toolbar_share);
        mIvright.setImageResource(R.drawable.ic_download);
        mTvNum = (TextView) findViewById(R.id.toolbar_tv_num);
        mRlNum = (LinearLayout) findViewById(R.id.toolbar_ll_num);

        mElv = (ExpandableListView) findViewById(R.id.adddownload_elv);
        mTvConfirm = (TextView) findViewById(R.id.adddownload_start_cache);
        mTvCheckAll = (TextView) findViewById(R.id.adddownload_check_all);
        mTvsd = (TextView) findViewById(R.id.adddownload_bottom_tv);
        mRxManager = new RxManager();
        initData();
        regEvent(true);
        Tracker_Google.getInstance().addGoogleScreenName("课程下载");
    }

    public void initData() {
        getIntentData();
        mDownloadManager = DownloadService.getDownloadManager();
        //getDefinition();
        mCheckedChildlist = new ArrayList<>();
        mDBHelper = new DBHelper(mContext);
        mElv.setGroupIndicator(null);
        mAdapter = new AddDownLoadAdapter(mContext);
        mElv.setAdapter(mAdapter);
        //toGetCourseTree();
        parse(mBean);
        toGetUnDownloadedFromDB();
    }

    private void getIntentData() {
        Intent intent = getIntent();
        this.mCourseid = intent.getStringExtra(COURSE_ID);
        CourseTrainDirBean serializableExtra = (CourseTrainDirBean) intent.getSerializableExtra(COURSE_BEAN);
        Gson gson = new Gson();
        String s = gson.toJson(serializableExtra);
        this.mBean = (EntityBean) JSONSerializer.getInstance().DeSerialize(s, EntityBean.class);
    }

    public void regEvent(boolean b) {
        if (mElv != null) {
            mElv.setOnChildClickListener(b ? this : null);
        }
        if (mTvConfirm != null) {
            mTvConfirm.setOnClickListener(b ? this : null);
            mTvConfirm.setClickable(false);
        }
        if (mTvCheckAll != null) {
            mTvCheckAll.setOnClickListener(b ? this : null);
        }
        mRlright.setOnClickListener(this);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();

            }
        });

    }

    /**
     * 获取sd卡的剩余
     */
    private void getSdRemain() {
        mSdsubscribe = Observable.interval(0, 1000, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .map(new Function<Long, String>() {
                    @Override
                    public String apply(Long aLong) throws Exception {
                        File file = Environment.getExternalStorageDirectory();
                        long usableSpace = file.getUsableSpace();
                        String size = Formatter.formatFileSize(mContext, usableSpace);
                        return size;
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        mTvsd.setText(AppUtil.getString(R.string.downloaded_sjsy) + s);
                    }
                });
        mRxManager.addDisposable(mSdsubscribe);
    }

    /**
     * 缓存课程图片
     */
    private void toDownloadpic() {
        String ImagePath = FolderConstants.VIDEO_DIR + UserInfor.getInstance().getUserid() + "/" + mCourseid + ".jpg";
        File file = new File(ImagePath);
        PrintLog.d(TAG, "IMAGELENGTH:" + file.length());
        if (!file.exists()) {
            toDownloadPic(mCourseid);
        } else if (!(file.length() > 0)) {
            toDownloadPic(mCourseid);
        }
    }


    /**
     * 从数据库中获取还未下载完成的数量
     */
    private synchronized void toGetUnDownloadedFromDB() {
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                e.onNext(getUnDownloadedFromDBIO());
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                       mRxManager.addDisposable(d);
                    }

                    @Override
                    public void onNext(Integer num) {
                        if (num == 0) {
                            mRlNum.setVisibility(View.INVISIBLE);
                        } else {
                            mRlNum.setVisibility(View.VISIBLE);
                            if (num > 99) {
                                mTvNum.setText("•••");
                            } else {
                                mTvNum.setText(num + "");
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    /**
     * 数据库获取未下载的数量
     */
    private int getUnDownloadedFromDBIO() {
        SQLiteDatabase db = null;
        Cursor cursor = null;
        int num = 0;
        try {
            db = mDBHelper.getWritableDatabase();
            cursor = db.rawQuery("select * from " + DownloadConstants.TBNAME_DOWNLOAD_DETAIL +
                    " where userID = ?", new String[]{UserInfor.getInstance().getUserid()});
            while (cursor.moveToNext()) {
                String cwID = cursor.getString(cursor.getColumnIndex("cwID"));
                boolean hasDownloaded = FileUtil.isHasDownloaded(mContext, UserInfor.getInstance().getUserid(), cwID);
                if (!hasDownloaded) {
                    num++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (db != null) {
                db.close();
            }
            if (cursor != null) {
                cursor.close();
            }
        }
        return num;
    }

    /**
     * 去获得课程树
     */
    private void toGetCourseTree() {
        String cardno = UserInfor.getInstance().getUsersfzh();
        String courseid = mCourseid; // "48c5d2b7f12a830de624483bb340ffd5"
        PrintLog.d(TAG, "cardno:" + cardno);
        EntityBean bean = new EntityBean();
        bean.set("cardno", cardno);
        bean.set("courseid", courseid);
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        DZZWTools.showWaitDialog(mContext);
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_course_sTrainResDirStructBean", fbean, new LoadDataManager.OnRequestCallListener() {

            @Override
            public void onSuccess(String key, String service, Object result) {
                parseCourseTreeData(result);
            }

            @Override
            public void onFinished(String key, String service) {
                DZZWTools.dismissDialog(null);
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {

            }
        });
    }

    private void parse(final EntityBean bean) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                parseCourseTreeData(bean);
                e.onNext("");
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mRxManager.addDisposable(d);
                        DZZWTools.showNotBackWaitDialog(mContext);
                    }

                    @Override
                    public void onNext(String value) {
                        toCheckIfHasAllDownloaded();
                        mAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {
                        DZZWTools.dismissNotBackDialog();
                    }

                    @Override
                    public void onComplete() {
                        DZZWTools.dismissNotBackDialog();
                    }
                });


    }

    private void parseCourseTreeData(Object result) {
        try {
            if (result != null) {
                EntityBean bean = (EntityBean) result;
                PrintLog.d(TAG, "BEANRESULT:" + bean.toString());
                String resultdesc = (String) bean.get("resultdesc");
                int resultstate = bean.getInt("resultstate");
                EntityBean resultbean = bean.getBean("result");
                if (resultstate == 1) {
                    mCurriclunTitles = new ArrayList<CurriclunTitle>();
                    mCurrcluSubTitlesList = new ArrayList<List<CurrcluSubTitle>>();
                    mCourseName = resultbean.getString("name");
                    mCourseImageUrl = resultbean.getString("realpic"); //课程图片

                    toDownloadpic(); //下载课程的封面

                    mExpiretime = resultbean.getString("expiretime"); //过期时间
                    String teacherJsonString = resultbean.getString("teacher");
                    if (teacherJsonString != null) {
                        try {
                            JSONArray teacherArray = new JSONArray(teacherJsonString);
                            if (teacherArray != null && !teacherArray.isNull(0)) {
                                JSONObject teacher = teacherArray.getJSONObject(0);
                                mTeachername = teacher.getString("teachername");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        mTeachername = "保博士";
                    }

                    EntityBean[] dirs = resultbean.getBean("traindirstruct").getBeans("dirinfo");
                    for (EntityBean dir : dirs) {
                        CurriclunTitle title = new CurriclunTitle();
                        title.setTitle(dir.getString("name"));
                        mCurriclunTitles.add(title);
                        String mdirid = dir.getString("dirid"); // 目录id
                        List<CurrcluSubTitle> currcluSubTitles = new ArrayList<CurrcluSubTitle>();
                        EntityBean[] nextDirs = dir.getBeans("nextnodeinfo");
                        if (nextDirs != null) {  //如果没有子item 就不要遍历
                            for (EntityBean nextDirBean : nextDirs) {
                                PrintLog.d(TAG, "nextDirBean:" + nextDirBean.toString());
                                String mCwid = nextDirBean.getString("cwid"); // 课件id
                                CurrcluSubTitle subTitle = new CurrcluSubTitle();
                                subTitle.setIdI(nextDirBean.getString("id"));
                                subTitle.setIsfinish(nextDirBean.getBoolean("isfinish"));
                                subTitle.setVideopass(nextDirBean.getBoolean("videopass"));//当前视频是否通过
                                subTitle.setHasqa(nextDirBean.getBoolean("hasqa"));//是否有课后练习题
                                subTitle.setTitle(nextDirBean.getString("name")); //课件名称
                                subTitle.setPathno(nextDirBean.getString("pathno"));
                                subTitle.setTotaltraintime(nextDirBean.getDouble("totaltraintime"));
                                subTitle.setCourseImageUrl(mCourseImageUrl);
                                subTitle.setCourseid(mCourseid);
                                subTitle.setCwid(mCwid);
                                subTitle.setChapterName(dir.getString("name"));//章节名称
                                subTitle.setChapterId(mdirid); //章节ID
                                String userid = UserInfor.getInstance().getUserid();
                                PrintLog.d(TAG, "userid:" + userid);
                                // 设置缓存的路径
                                subTitle.setCachePath(FolderConstants.VIDEO_DIR + userid + "/" + mCourseid + "/" + mdirid + "/" + mCwid + ".mp4");
                                // 设置缓存文件夹
                                subTitle.setCacheFolderPath(FolderConstants.VIDEO_DIR + userid + "/" + mCourseid + "/" + mdirid);

                                PrintLog.d(TAG, "CachePath:" + FolderConstants.VIDEO_DIR + userid + "/" + mCourseid + "/" + mdirid + "/" + mCwid + ".mp4");
                                String video = nextDirBean.getString("cwstyle");//20170814 判断该课件能否下载 学历教育的是不能下载的
                                if("video".equals(video)){
                                    currcluSubTitles.add(subTitle);
                                }

                            }

                        }
                        mCurrcluSubTitlesList.add(currcluSubTitles);
                    }


                    for (int x = 0; x < mCurrcluSubTitlesList.size(); x++) {
                        for (int y = 0; y < mCurrcluSubTitlesList.get(x).size(); y++) {
                            CurrcluSubTitle childItem = mCurrcluSubTitlesList.get(x).get(y);
                            toCheckIfSaveToDB(childItem); //判断哪些item有下载过
                        }
                    }


                    //给数据库添加课程数据
                    //getIfHasCourseFromCourseDB(mCourseid);
                    mAdapter.setData(mCurriclunTitles, mCurrcluSubTitlesList);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 检查是否已经添加到缓存列表
     */
    private boolean toCheckIfSaveToDB(CurrcluSubTitle childItem) {
        boolean isSaveSuccess = false;
        db = mDBHelper.getWritableDatabase();
        Cursor cursor = null;
        try {
            cursor = db.rawQuery("select * from " + DownloadConstants.TBNAME_DOWNLOAD_DETAIL +
                    " where userID = ? and courseID = ? and cwID = ?", new String[]{UserInfor.getInstance().getUserid(), childItem.getCourseid(), childItem.getCwid()});

            if (cursor.moveToNext()) {
                childItem.setIsDownloaded(true);
                isSaveSuccess = true;
            } else {
                childItem.setIsDownloaded(false);
            }
        } catch (Exception e) {

        } finally {
            if (db != null) {
                db.close();
            }
            if (cursor != null) {
                cursor.close();
            }
        }
        return isSaveSuccess;
    }

    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        PrintLog.d(TAG, "groupPosition+childPosition:" + groupPosition + ":" + childPosition);
        CurrcluSubTitle childItem = mCurrcluSubTitlesList.get(groupPosition).get(childPosition);
        if (!childItem.isDownloaded()) { //如果本地已经加载了视频 则用户点击无效
            if (childItem.isCheck()) {
                childItem.setCheck(false);
                mCheckedChildlist.remove(childItem);
                mIsCheckAll = true;
                toChangeButtonStatus();
            } else {
                childItem.setCheck(true);
                if (!mCheckedChildlist.contains(childItem)) {
                    childItem.setParentPosition(groupPosition);
                    childItem.setChildPosition(childPosition);
                    mCheckedChildlist.add(childItem);
                    if (mCheckedChildlist.size() == getCanCheckedNum()) {
                        mIsCheckAll = false;
                        toChangeButtonStatus();
                    }
                }
            }
        } else {
            DZZWTools.showToast(mContext, "该视频已加入缓存", 0);
        }

        showConfirmBt();
        mAdapter.notifyDataSetChanged();
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.adddownload_start_cache: //确定缓存
                judgeNetwork();
                break;
            case R.id.adddownload_check_all: //全选
                toCheckAll();
                break;
            case R.id.bb_toolbar_right_rl: //进入下载管理页面
                Intent intent = new Intent(mContext, DownloadedManageActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
                break;
            case R.id.text_cancle:   //取消在移动网络下下载
                DialogUtil.getInstance().dismiss();
                break;
            case R.id.text_confirm:  //确认在移动网络下下载
                DialogUtil.getInstance().dismiss();
                prepareDownload();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            initData();
            showConfirmBt();
            mIsCheckAll = true;
            toChangeButtonStatus();
        }
    }

    private void judgeNetwork() {
        //判断有没有网络
        if (!NetUtil.checkNetEnable()) {
            return;
        }
        boolean canMobileDownload = Control.isCanMobileDownload();
        //判断当前网络是否是移动网络
        if (!canMobileDownload && NetUtil.isDataNet(mContext)) {
            View v = View.inflate(mContext, R.layout.dialog_exit, null);
            TextView cacnle_3g = (TextView) v.findViewById(R.id.text_cancle);
            TextView confrim_3g = (TextView) v.findViewById(R.id.text_confirm);
            TextView title = (TextView) v.findViewById(R.id.dialog_hint);
            TextView msg = (TextView) v.findViewById(R.id.text_m);
            title.setText("提示");
            msg.setText("您当前处于非wifi网络环境下，继续使用可能产生流量");
            cacnle_3g.setOnClickListener(this);
            confrim_3g.setOnClickListener(this);
            DialogUtil.getInstance().creatAlertDialog(mContext, v, 266, 159);
        } else {
            prepareDownload();
        }

    }

    /**
     * 准备下载
     */
    private void prepareDownload() {
        mNeedToDownChildlist = new ArrayList<>();
        mNeedToDownChildlist.clear();
        mNeedToDownChildlist.addAll(mCheckedChildlist);
        DZZWTools.showWaitDialog(mContext);
        toSavaCourseDB(mCourseid);
        mTvConfirm.setClickable(false);
        toCache();
    }


    /**
     * 检查设置的本地缓存够不够
     */
    private boolean toCheckIfHasCache() {
        String path = FolderConstants.VIDEO_DIR + "/" + UserInfor.getInstance().getUserid();
        File file = new File(path);
        try {
            long folderSize = FileUtil.getFolderSize(file);
            String cacheMaxSize = Control.getCacheMaxSize();
            long maxSize = Long.parseLong(cacheMaxSize) * 1024 * 1024;
            PrintLog.d(TAG, "folderSize:" + folderSize);
            PrintLog.d(TAG, "cacheMaxSize:" + maxSize);
            if (folderSize >= maxSize) {
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 在确定缓存的按钮上面实时显示已经选择需要下载的数量
     */
    private void showConfirmBt() {
        if (mCheckedChildlist.size() > 0) {
            mTvConfirm.setText("确定缓存(" + mCheckedChildlist.size() + ")");
            mTvConfirm.setClickable(true);
            mTvConfirm.setBackgroundResource(R.drawable.selecter_bt_cache_start);
        } else {
            mTvConfirm.setText("确定缓存");
            mTvConfirm.setClickable(false);
            mTvConfirm.setBackgroundColor(Color.parseColor("#A0A0A0"));
        }
    }

    /**
     * 获取能选择的item数量
     *
     * @return
     */
    private int getCanCheckedNum() {
        int num = 0;
        for (int i = 0; i < mCurrcluSubTitlesList.size(); i++) {
            for (int j = 0; j < mCurrcluSubTitlesList.get(i).size(); j++) {
                CurrcluSubTitle childItem = mCurrcluSubTitlesList.get(i).get(j);
                if (!childItem.isDownloaded()) { //已经下载的就不要选择了
                    num++;
                }

            }
        }
        return num;
    }

    /**
     * 全选
     */
    private void toCheckAll() {
        for (int i = 0; i < mCurrcluSubTitlesList.size(); i++) {
            for (int j = 0; j < mCurrcluSubTitlesList.get(i).size(); j++) {
                CurrcluSubTitle childItem = mCurrcluSubTitlesList.get(i).get(j);
                if (mIsCheckAll) { //已经全选了 就取消全选
                    childItem.setCheck(false);
                    mCheckedChildlist.remove(childItem);
                } else {
                    if (!childItem.isDownloaded()) { //已经下载的就不要选择了
                        childItem.setCheck(true);
                        if (!mCheckedChildlist.contains(childItem)) {
                            mCheckedChildlist.add(childItem);
                        }
                    }
                }
            }
        }
        toChangeButtonStatus();
        showConfirmBt();
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 判断是否全部都下载了
     */
    private void toCheckIfHasAllDownloaded() {
        boolean isHasAlldownload = true;
        for (int i = 0; i < mCurrcluSubTitlesList.size(); i++) {
            for (int j = 0; j < mCurrcluSubTitlesList.get(i).size(); j++) {
                CurrcluSubTitle childItem = mCurrcluSubTitlesList.get(i).get(j);
                if (!childItem.isDownloaded()) {
                    isHasAlldownload = false;
                    break;
                }
            }
        }
        if (isHasAlldownload) {
            mTvCheckAll.setClickable(false);
            mTvCheckAll.setBackgroundColor(Color.parseColor("#A0A0A0"));
        } else {
            mTvCheckAll.setClickable(true);
            mTvCheckAll.setBackgroundResource(R.drawable.selecter_bt_cache_start);
        }
    }


    /**
     * 切换全选按钮的状态
     */
    private void toChangeButtonStatus() {
        if (mIsCheckAll) {
            mIsCheckAll = false;
            mTvCheckAll.setText("全选");
        } else {
            mIsCheckAll = true;
            mTvCheckAll.setText("取消全选");
        }
    }

    /**
     * 缓存课程
     */
    private void toCache() {
        PrintLog.d(TAG, "mNeedToDownChildlist.size():" + mNeedToDownChildlist.size());
        if (mNeedToDownChildlist.size() > 0) {
            CurrcluSubTitle currcluSubTitle = mNeedToDownChildlist.get(0);
            toGetDownloadcourse(currcluSubTitle);
        } else {
            if (mCheckedChildlist.size() > 0) {  //如果出现意外没有添加到数据库的item重新添加到数据库并且下载
                mNeedToDownChildlist.addAll(mCheckedChildlist);
                toCache();
            }
            mIsCheckAll = true;
            toChangeButtonStatus();
            toGetUnDownloadedFromDB();
            DZZWTools.dismissDialog(null);
            DZZWTools.showToast(mContext, "成功添加至缓存列表", 0);
            mTvConfirm.setClickable(false);
            toCheckIfHasAllDownloaded();
        }

    }

    /**
     * 从课程数据库中查询课程是否有缓存
     * 如果没有缓存需要把图片下载下来然后再将数据写入数据库
     *
     * @return
     */
    private void getIfHasCourseFromCourseDB(String courseID) {
        db = mDBHelper.getWritableDatabase();
        localCourseImagePath = FolderConstants.VIDEO_DIR + UserInfor.getInstance().getUserid() + "/" + mCourseid + ".jpg";
        Cursor cursor = db.rawQuery("SELECT * FROM " + DownloadConstants.TBNAME_DOWNLOAD_COURSE + " where userID = ? and courseID = ?", new String[]{UserInfor.getInstance().getUserid(), courseID});
        if (cursor.moveToNext()) { //数据库里面有缓存当前课程 当前课程无需再缓存 也无需向课程数据库添加数据
            String imagePath = cursor.getString(cursor.getColumnIndex("imagePath"));
            if (imagePath == null) {
                toDownloadPic(courseID);
            }
        } else {  //数据库没有当前课程 就去缓存图片 添加课程
            cursor.close();
            db.close();
            toDownloadPic(courseID);
        }
    }

    /**
     * 下载封面
     */
    private void toDownloadPic(final String courseID) {
//        PrintLog.d(TAG, "courseurl:" + mCourseImageUrl);
//        LoadDataManager.getInstance(mContext).setUserflag(UserInfor.getInstance().getUserid());
//        LoadDataManager.getInstance(mContext).downLoadFile(mCourseImageUrl, mCourseid + ".jpg", new OnDownLoadFileListener() {
//            @Override
//            public void downLoadStar(float totalSize) {
//
//            }
//
//            @Override
//            public void downLoadProgerss(float progress, float downLoad, float totalSize) {
//
//            }
//
//            @Override
//            public void downLoadSuccess(LoadFileRunnable loadFileRunnable) {
//
//            }
//
//            @Override
//            public void downLoadFailure(LoadFileRunnable loadFileRunnable) {
//
//            }
//        });
    }

    /**
     * 将课程的数据存到课程的数据库
     */
    private void toSavaCourseDB(String courseID) {
        ContentValues cv = new ContentValues();
        cv.put(DownloadConstants.USERID, UserInfor.getInstance().getUserid());
        cv.put(DownloadConstants.COURSEID, mCourseid);
        cv.put(DownloadConstants.IMAGEPATH, localCourseImagePath);
        cv.put(DownloadConstants.COURSENAME, mCourseName);
        cv.put(DownloadConstants.TEACHER, mTeachername);
        Cursor cursor = null;
        try {
            db = mDBHelper.getWritableDatabase();
            cursor = db.rawQuery("SELECT * FROM " + DownloadConstants.TBNAME_DOWNLOAD_COURSE + " where userID = ? and courseID = ?", new String[]{UserInfor.getInstance().getUserid(), courseID});
            if (cursor.moveToNext()) {
                db.update(DownloadConstants.TBNAME_DOWNLOAD_COURSE, cv, "userID = ? and courseID = ?", new String[]{UserInfor.getInstance().getUserid(), courseID});
            } else {
                db.insert(DownloadConstants.TBNAME_DOWNLOAD_COURSE, null, cv);
            }
        } catch (Exception e) {

        } finally {
            if (db != null) {
                db.close();
            }
            if (cursor != null) {
                cursor.close();
            }
        }
    }


    /**
     * 下载已经选择的课程
     */
    private void toGetDownloadcourse(final CurrcluSubTitle childItem) {
        deifinition = CacheUtils.getString(UserInfor.getInstance().getUsersfzh() + "cachedefinition", "1");
        EntityBean bean = new EntityBean();

        if (childItem == null) {
            return;
        }

        String cwid = childItem.getCwid();
        String pathno = childItem.getPathno();
        String usersfzh = UserInfor.getInstance().getUsersfzh();


        PrintLog.d(TAG, "cwid1:" + cwid);
        PrintLog.d(TAG, "courseid1:" + mCourseid);
        PrintLog.d(TAG, "pathno1:" + pathno);
        PrintLog.d(TAG, "usersfzh1:" + usersfzh);

        bean.set("cardno", usersfzh);
        bean.set("pathno", pathno);
        bean.set("courseid", mCourseid);
        bean.set("cwid", cwid);
        bean.set("isdownload", "1");
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        LoadDataManager.getInstance().callService("", UrlConstants.BaseUrl, "bbt_course_sVideoPlayBeanByAndroid", fbean, new LoadDataManager.OnRequestCallListener() {

            @Override
            public void onSuccess(String key, String service, Object result) {
                parseResult(result, childItem);
            }

            @Override
            public void onFinished(String key, String service) {
                PrintLog.d(TAG, "finish1:" + key);
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                mNeedToDownChildlist.remove(0);
                toCache();
            }
        });
    }

    /**
     * 解析请求网络下载地址的数据
     *
     * @param result
     */
    private void parseResult(Object result, CurrcluSubTitle childItem) {
        try {
            EntityBean bean = (EntityBean) result;
            PrintLog.d(TAG, "bean::" + bean.toString());
            int resultstate = bean.getInt("resultstate");
            if (resultstate == 1) {
                EntityBean resultbean = bean.getBean("result");
                EntityBean videoinfobean = resultbean.getBean("videoinfo");
                EntityBean cwnodeinfobean = videoinfobean.getBean("cwnodeinfo");
                String pathno = cwnodeinfobean.getString("pathno");//当前节点编号


                boolean isvideoinfonormal = resultbean.getBoolean("isvideoinfonormal");
                if (isvideoinfonormal) {
                    EntityBean videoinfo = resultbean.getBean("videoinfo");
                    // 更新学习记录缓存
                    EntityBean studyrecordinfo = resultbean.getBean("studyrecordinfo");
                    double effecttime = studyrecordinfo.getDouble("effecttime");
                    String id = studyrecordinfo.getString("id");
                    String studentno = studyrecordinfo.getString("studentno");
                    EntityBean videoattr = videoinfo.getBean("videoattr");
                    EntityBean[] videomain = videoattr.getBeans("videomain");
                    int length = videomain.length;
                    if (length == 0) {
                        return;
                    }
                    EntityBean videoSourceBean = null;
                    PrintLog.d(TAG, "deifinition:" + deifinition);
                    if ("0".equals(deifinition)) { // 高清
                        videoSourceBean = videomain[length - 1];
                    } else {
                        videoSourceBean = videomain[0];
                        PrintLog.d(TAG, "videoSourceBean:" + videoSourceBean);
                    }

                    if (videoSourceBean != null) {
                        String vsource = videoSourceBean.getString("vsource");
                        PrintLog.d(TAG, "vsource:" + vsource);
                        childItem.setPathnojd(pathno);
                        childItem.setIdI(id);
                        childItem.setExpiretime(mExpiretime);
                        childItem.setEffecttime(effecttime);
                        childItem.setStudentno(studentno);

                        String path = toGetIfHasSameURL(vsource);
                        if (!TextUtils.isEmpty(path)) {
                            childItem.setCachePath(path);
                        }
                        saveToDB(vsource, childItem, 0, 0); //将视频的url保存到数据库
                        boolean isSaveSuccess = toCheckIfSaveToDB(childItem);
                        toGetUnDownloadedFromDB();
                        if (TextUtils.isEmpty(path)) {
                            toDownloadcourse(vsource, childItem);
                        }
                        if (mCheckedChildlist.contains(childItem) && isSaveSuccess) {
                            mCheckedChildlist.remove(childItem);
                        }

                        showConfirmBt();
                        toCheckIfHasAllDownloaded();
                        mAdapter.notifyDataSetChanged();
                    }

                }
            }
            mNeedToDownChildlist.remove(0);
            toCache();
        } catch (Exception e) {
            saveToDB("", childItem, 0, 0); //将视频的url保存到数据库
            boolean isSaveSuccess = toCheckIfSaveToDB(childItem);
            if (mCheckedChildlist.contains(childItem) && isSaveSuccess) {
                mCheckedChildlist.remove(childItem);
            }
            showConfirmBt();
            toCheckIfHasAllDownloaded();
            mAdapter.notifyDataSetChanged();

            mNeedToDownChildlist.remove(0);
            toCache();
            PrintLog.d(TAG, "EEEEE:" + e.toString());
        }

    }

    /**
     * 通过视频的url来判断本地是否有缓存相同的视频
     */
    private String toGetIfHasSameURL(String url) {
        SQLiteDatabase db = null;
        Cursor cursor = null;
        String cachepath = null;
        try {
            db = mDBHelper.getWritableDatabase();
            cursor = db.rawQuery("select * from " + DownloadConstants.TBNAME_DOWNLOAD_DETAIL +
                    " where userID = ? and downloadurl = ?", new String[]{UserInfor.getInstance().getUserid(), url});
            if (cursor.moveToNext()) {
                cachepath = cursor.getString(cursor.getColumnIndex("cachepath"));
            }
        } catch (Exception e) {
            PrintLog.d(TAG, "E22::" + e.toString());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
        return cachepath;
    }


    /**
     * 将需要缓存的数据添加到数据库
     */
    private void saveToDB(String url, CurrcluSubTitle childItem, float downloadedlength, float totalLength) {
        ContentValues cv = new ContentValues();
        cv.put(DownloadConstants.USERID, UserInfor.getInstance().getUserid());
        cv.put(DownloadConstants.COURSEID, childItem.getCourseid());
        cv.put(DownloadConstants.COURSENAME, mCourseName);
        cv.put(DownloadConstants.POSITION, ((childItem.getParentPosition() * 100) + childItem.getChildPosition()));
        cv.put(DownloadConstants.URL, url);
        cv.put(DownloadConstants.CACHEPATH, childItem.getCachePath());
        cv.put(DownloadConstants.DOWNLOADEDLENGTH, downloadedlength);
        cv.put(DownloadConstants.TOTALLENGTH, totalLength);
        cv.put(DownloadConstants.CHAPTERNAME, childItem.getChapterName());
        cv.put(DownloadConstants.CWNAME, childItem.getTitle());
        cv.put(DownloadConstants.CWID, childItem.getCwid());
        cv.put(DownloadConstants.ID, childItem.getId());
        cv.put(DownloadConstants.EXPIRETIME, childItem.getExpiretime());
        cv.put(DownloadConstants.EFFECTTIME, childItem.getEffecttime());
        cv.put(DownloadConstants.STUDENTNO, childItem.getStudentno());
        cv.put(DownloadConstants.CHAPTERID, childItem.getChapterId());
        cv.put(DownloadConstants.TOTALTRAINTIME, childItem.getTotaltraintime());
        cv.put(DownloadConstants.PATHNO, childItem.getPathnojd());

        if (childItem.isIsfinish()) {
            cv.put(DownloadConstants.ISFINISHED, 1);
        } else {
            cv.put(DownloadConstants.ISFINISHED, 0);
        }

        if (childItem.isVideopass()) {
            cv.put(DownloadConstants.VIDEOPASS, 1);
        } else {
            cv.put(DownloadConstants.VIDEOPASS, 0);
        }

        if (childItem.isHasqa()) {
            cv.put(DownloadConstants.HASQA, 1);
        } else {
            cv.put(DownloadConstants.HASQA, 0);
        }


        String partPath = "/" + mCourseid + "/" + childItem.getChapterId() + "/" + childItem.getCwid() + ".mp4";
        cv.put(DownloadConstants.PARTPATH, partPath);
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = mDBHelper.getWritableDatabase();
            PrintLog.d(TAG, "userID:" + UserInfor.getInstance().getUserid());
            PrintLog.d(TAG, "courseID:" + childItem.getCourseid());
            PrintLog.d(TAG, "cwID:" + childItem.getCwid());
            cursor = db.rawQuery("select * from " + DownloadConstants.TBNAME_DOWNLOAD_DETAIL + " where userID = ? and courseID = ? and cwID = ?", new String[]{UserInfor.getInstance().getUserid(), childItem.getCourseid(), childItem.getCwid()});
            if (cursor.moveToNext()) {
                db.update(DownloadConstants.TBNAME_DOWNLOAD_DETAIL, cv, " userID = ? and courseID = ? and cwID = ?", new String[]{UserInfor.getInstance().getUserid(), childItem.getCourseid(), childItem.getCwid()});
            } else {
                db.insert(DownloadConstants.TBNAME_DOWNLOAD_DETAIL, null, cv);
            }
        } catch (Exception e) {
            PrintLog.d(TAG, "EXCEPTION2:" + e.toString());
        } finally {
            if (db != null) {
                db.close();
            }
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    /**
     * 下载视频
     */
    private void toDownloadcourse(final String videourl, final CurrcluSubTitle childItem) {
        FileUtil.createFolder(childItem.getCacheFolderPath());
        String cachePath = childItem.getCachePath();
        PrintLog.d(TAG, "videourl:" + videourl);
        mDownloadManager.addTask(videourl, cachePath);
    }

    @Override
    public void finish() {
        super.finish();
        AddDownloadActivity.this.overridePendingTransition(R.anim.activity_up_down_open2,
                R.anim.activity_up_down_close);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mRxManager != null) {
            mRxManager.removeDisposable(mSdsubscribe);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
